package com.wswy.wzcx.ui.fkdj

import android.app.Activity
import android.app.DatePickerDialog
import android.arch.lifecycle.Observer
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import com.blankj.utilcode.util.SizeUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.ui.other.FineNoTextWatcher
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import com.wswy.wzcx.utils.FileUtils
import com.wswy.wzcx.utils.FrescoUtils
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.StringUtils
import com.wswy.wzcx.widget.utils.MoneyTextWatcher
import com.wzcx.orclib.MaskConfig
import com.wzcx.orclib.PhotoAgent
import kotlinx.android.synthetic.main.fragment_fkdj_edit.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 手动输入罚单信息
 */
@Deprecated("")
class FineEditFragment : CBaseFragment() {

    private companion object {
        private const val REQ_CHOOSE_PHOTO = 71
    }

    private lateinit var fineViewModel: FineViewModel

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_fkdj_edit
    }

    private var fineFee:String?=null
    private var fineDate:String?=null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        fineViewModel = provideViewModelFromActivity(FineViewModel::class.java)

        et_fine_fee.addTextChangedListener(MoneyTextWatcher())
        et_fine_fee.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL

        rl_fine_date.setOnClickListener {
            showChooseDate()
        }
        img_add.setOnClickListener {
            startChoosePhoto()
        }

        bindData()
    }


    private fun bindData(){



        et_fine_name.requestFocus()

        tv_no_hint.setOnClickListener {
            DialogFactory.showHelp(it.context,R.drawable.chujuebianma)
        }

        et_fine_no.addTextChangedListener(FineNoTextWatcher(et_fine_no))
        et_fine_no.addTextChangedListener(object : TextWatcherIMPL(){
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                getCurrFine()?.fineNo = FineNoTextWatcher.getRealFineNumber(et_fine_no)
            }
        })

        et_fine_fee.addTextChangedListener(object :TextWatcherIMPL(){

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                getCurrFine()?.setFineFee(s)
                fineFee = s?.toString()
                totalFee()
            }
        })

        et_fine_name.addTextChangedListener(object :TextWatcherIMPL(){
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                super.onTextChanged(s, start, before, count)
                getCurrFine()?.fineName = s?.toString()
            }
        })

        fineViewModel.getFineLiveData().observe(this, Observer {

            it?.run {
                tv_fine_late_amount.text = getString(R.string.amount_args,StringUtils.formatMoney(lateFee.toDouble()))
            }
        })

        fineViewModel.getFineLiveData().value?.run {

            et_fine_no.setText(fineNo)

            fineNo?.let {
                fineViewModel.checkFineArea(it)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_PHOTO){
            val saveFile = FileUtils.getSaveFile(context)

            if (saveFile.exists()) {
                FrescoUtils.removeCache(Uri.fromFile(saveFile))
                ImageUtils.showImage(img_add,saveFile)

                getCurrFine()?.photo = saveFile.absolutePath

                //saveFile.absolutePath
            }
        }
    }


    private fun getCurrFine() = fineViewModel.getFineLiveData().value

    private var chooseCalendar:Calendar?=null
    private val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    private fun showChooseDate() {
        val context = context
        val calendar = Calendar.getInstance()

        var year = Math.max(calendar.get(Calendar.YEAR), 2018)
        var month = 0
        var dayOfM = 1

        chooseCalendar?.run {
            year = get(Calendar.YEAR)
            month = get(Calendar.MONTH)
            dayOfM = get(Calendar.DAY_OF_MONTH)
        }


        val datePickerDialog = DialogFactory.createDatePickerDialog(context, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
            if (chooseCalendar == null) {
                chooseCalendar = Calendar.getInstance()
            }
            chooseCalendar?.run {
                set(Calendar.YEAR, year)
                set(Calendar.MONTH, month)
                set(Calendar.DAY_OF_MONTH, dayOfMonth)

                val date= format.format(time)

                fineDate = date

                getCurrFine()?.fineDate = date

                tv_fine_date.text = date

                totalFee()
            }

        }, year, month, dayOfM)
        val datePicker = datePickerDialog.datePicker
        datePicker.maxDate = calendar.timeInMillis
        datePickerDialog.show()
    }


    private fun startChoosePhoto(){
//        val maskConfig = MaskConfig()
//        maskConfig.title = "拍摄驾驶证正本正面"
//        maskConfig.subTitle = "避免反光影响，确保图像清晰，可以提高识别率"
//        maskConfig.cardTitle = "中华人民共和国机动车驾驶证"
//        maskConfig.cardHint = "将驾驶证主页置于此区域，并对齐左下角发证机关印章"
//
//        maskConfig.width = SizeUtils.dp2px(72f)
//        maskConfig.height = SizeUtils.dp2px(72f)
//        maskConfig.gravity = Gravity.LEFT

        startActivityForResult(PhotoAgent.getPhotoIntent(context,  FileUtils.getSaveFile(context).getAbsolutePath(), null), REQ_CHOOSE_PHOTO)

    }


    private fun totalFee(){

        if (TextUtils.isEmpty(fineFee) || TextUtils.isEmpty(fineDate)){
            //如果没填完整，默认为0
            getCurrFine()?.setLateFee("0")
            getCurrFine()?.setServiceFee("0")

            fineViewModel.reSendFineData()

            return
        }

        fineViewModel.countTotalFee()

    }

}